class LocationEntity {
  final String? city;
  final String? country;
  final List<double>? coordinates; // [longitude, latitude]
  final String? address; // 详细地址
  final DateTime? updatedAt; // 位置更新时间

  const LocationEntity({
    this.city,
    this.country,
    this.coordinates,
    this.address,
    this.updatedAt,
  });

  // 复制方法
  LocationEntity copyWith({
    String? city,
    String? country,
    List<double>? coordinates,
    String? address,
    DateTime? updatedAt,
  }) {
    return LocationEntity(
      city: city ?? this.city,
      country: country ?? this.country,
      coordinates: coordinates ?? this.coordinates,
      address: address ?? this.address,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'city': city,
      'country': country,
      'coordinates': coordinates,
      'address': address,
      'updatedAt': updatedAt?.toIso8601String(),
    };
  }

  // 从JSON创建
  factory LocationEntity.fromJson(Map<String, dynamic> json) {
    return LocationEntity(
      city: json['city'],
      country: json['country'],
      coordinates: json['coordinates']?.cast<double>(),
      address: json['address'],
      updatedAt:
          json['updatedAt'] != null ? DateTime.parse(json['updatedAt']) : null,
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is LocationEntity &&
          runtimeType == other.runtimeType &&
          city == other.city &&
          country == other.country;

  @override
  int get hashCode => city.hashCode ^ country.hashCode;
}

class UserPreferencesEntity {
  final String language;
  final String theme;
  final Map<String, bool> notifications;
  final bool locationTracking; // 位置跟踪
  final bool publicProfile; // 公开资料

  const UserPreferencesEntity({
    this.language = 'zh',
    this.theme = 'auto',
    this.notifications = const {
      'email': true,
      'push': true,
      'follows': true,
      'likes': true,
      'comments': true,
    },
    this.locationTracking = true,
    this.publicProfile = true,
  });

  // 复制方法
  UserPreferencesEntity copyWith({
    String? language,
    String? theme,
    Map<String, bool>? notifications,
    bool? locationTracking,
    bool? publicProfile,
  }) {
    return UserPreferencesEntity(
      language: language ?? this.language,
      theme: theme ?? this.theme,
      notifications: notifications ?? this.notifications,
      locationTracking: locationTracking ?? this.locationTracking,
      publicProfile: publicProfile ?? this.publicProfile,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'language': language,
      'theme': theme,
      'notifications': notifications,
      'locationTracking': locationTracking,
      'publicProfile': publicProfile,
    };
  }

  // 从JSON创建
  factory UserPreferencesEntity.fromJson(Map<String, dynamic> json) {
    return UserPreferencesEntity(
      language: json['language'] ?? 'zh',
      theme: json['theme'] ?? 'auto',
      notifications:
          json['notifications']?.cast<String, bool>() ??
          const {
            'email': true,
            'push': true,
            'follows': true,
            'likes': true,
            'comments': true,
          },
      locationTracking: json['locationTracking'] ?? true,
      publicProfile: json['publicProfile'] ?? true,
    );
  }
}

class UserEntity {
  final String id;
  final String username;
  final String name;
  final String email;
  final String? avatar;
  final String? bio;
  final String? phone; // 手机号
  final LocationEntity? location;
  final List<String> followers;
  final List<String> following;
  final int followersCount;
  final int followingCount;
  final bool isVerified;
  final bool isActive;
  final bool isOnline; // 在线状态
  final DateTime? lastLoginAt;
  final DateTime? lastSeenAt; // 最后在线时间
  final UserPreferencesEntity preferences;
  final DateTime createdAt;
  final DateTime? updatedAt;

  const UserEntity({
    required this.id,
    required this.username,
    required this.name,
    required this.email,
    this.avatar,
    this.bio,
    this.phone,
    this.location,
    this.followers = const [],
    this.following = const [],
    this.followersCount = 0,
    this.followingCount = 0,
    this.isVerified = false,
    this.isActive = true,
    this.isOnline = false,
    this.lastLoginAt,
    this.lastSeenAt,
    this.preferences = const UserPreferencesEntity(),
    required this.createdAt,
    this.updatedAt,
  });

  // 复制方法
  UserEntity copyWith({
    String? id,
    String? username,
    String? name,
    String? email,
    String? avatar,
    String? bio,
    String? phone,
    LocationEntity? location,
    List<String>? followers,
    List<String>? following,
    int? followersCount,
    int? followingCount,
    bool? isVerified,
    bool? isActive,
    bool? isOnline,
    DateTime? lastLoginAt,
    DateTime? lastSeenAt,
    UserPreferencesEntity? preferences,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return UserEntity(
      id: id ?? this.id,
      username: username ?? this.username,
      name: name ?? this.name,
      email: email ?? this.email,
      avatar: avatar ?? this.avatar,
      bio: bio ?? this.bio,
      phone: phone ?? this.phone,
      location: location ?? this.location,
      followers: followers ?? this.followers,
      following: following ?? this.following,
      followersCount: followersCount ?? this.followersCount,
      followingCount: followingCount ?? this.followingCount,
      isVerified: isVerified ?? this.isVerified,
      isActive: isActive ?? this.isActive,
      isOnline: isOnline ?? this.isOnline,
      lastLoginAt: lastLoginAt ?? this.lastLoginAt,
      lastSeenAt: lastSeenAt ?? this.lastSeenAt,
      preferences: preferences ?? this.preferences,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'username': username,
      'name': name,
      'email': email,
      'avatar': avatar,
      'bio': bio,
      'phone': phone,
      'location': location?.toJson(),
      'followers': followers,
      'following': following,
      'followersCount': followersCount,
      'followingCount': followingCount,
      'isVerified': isVerified,
      'isActive': isActive,
      'isOnline': isOnline,
      'lastLoginAt': lastLoginAt?.toIso8601String(),
      'lastSeenAt': lastSeenAt?.toIso8601String(),
      'preferences': preferences.toJson(),
      'createdAt': createdAt.toIso8601String(),
      'updatedAt': updatedAt?.toIso8601String(),
    };
  }

  // 从JSON创建
  factory UserEntity.fromJson(Map<String, dynamic> json) {
    return UserEntity(
      id: json['id'],
      username: json['username'],
      name: json['name'],
      email: json['email'],
      avatar: json['avatar'],
      bio: json['bio'],
      phone: json['phone'],
      location:
          json['location'] != null
              ? LocationEntity.fromJson(json['location'])
              : null,
      followers: json['followers']?.cast<String>() ?? [],
      following: json['following']?.cast<String>() ?? [],
      followersCount: json['followersCount'] ?? 0,
      followingCount: json['followingCount'] ?? 0,
      isVerified: json['isVerified'] ?? false,
      isActive: json['isActive'] ?? true,
      isOnline: json['isOnline'] ?? false,
      lastLoginAt:
          json['lastLoginAt'] != null
              ? DateTime.parse(json['lastLoginAt'])
              : null,
      lastSeenAt:
          json['lastSeenAt'] != null
              ? DateTime.parse(json['lastSeenAt'])
              : null,
      preferences:
          json['preferences'] != null
              ? UserPreferencesEntity.fromJson(json['preferences'])
              : const UserPreferencesEntity(),
      createdAt: DateTime.parse(json['createdAt']),
      updatedAt:
          json['updatedAt'] != null ? DateTime.parse(json['updatedAt']) : null,
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is UserEntity &&
          runtimeType == other.runtimeType &&
          id == other.id &&
          username == other.username &&
          email == other.email;

  @override
  int get hashCode => id.hashCode ^ username.hashCode ^ email.hashCode;

  @override
  String toString() {
    return 'UserEntity{id: $id, username: $username, name: $name, email: $email}';
  }

  // 检查是否关注某用户
  bool isFollowing(String userId) => following.contains(userId);

  // 检查是否被某用户关注
  bool isFollowedBy(String userId) => followers.contains(userId);

  // 获取用户位置信息
  String get locationDisplay {
    if (location?.city != null && location?.country != null) {
      return '${location!.city}, ${location!.country}';
    } else if (location?.city != null) {
      return location!.city!;
    } else if (location?.country != null) {
      return location!.country!;
    }
    return '未设置位置';
  }

  // 检查是否有地理坐标
  bool get hasCoordinates => location?.coordinates?.length == 2;

  // 获取经度
  double? get longitude => hasCoordinates ? location!.coordinates![0] : null;

  // 获取纬度
  double? get latitude => hasCoordinates ? location!.coordinates![1] : null;

  // 获取用户状态
  String get statusDisplay {
    if (isOnline) {
      return '在线';
    } else if (lastSeenAt != null) {
      final diff = DateTime.now().difference(lastSeenAt!);
      if (diff.inMinutes < 5) {
        return '刚刚在线';
      } else if (diff.inHours < 1) {
        return '${diff.inMinutes}分钟前在线';
      } else if (diff.inDays < 1) {
        return '${diff.inHours}小时前在线';
      } else {
        return '${diff.inDays}天前在线';
      }
    }
    return '离线';
  }

  // 检查位置是否需要更新（超过1小时）
  bool get needsLocationUpdate {
    if (location?.updatedAt == null) return true;
    final diff = DateTime.now().difference(location!.updatedAt!);
    return diff.inHours >= 1;
  }

  // 获取头像URL或占位符
  String get avatarUrl =>
      avatar ??
      'https://ui-avatars.com/api/?name=${Uri.encodeComponent(name)}&background=0D8ABC&color=fff';

  // 检查是否是新用户（注册不到7天）
  bool get isNewUser {
    final diff = DateTime.now().difference(createdAt);
    return diff.inDays < 7;
  }
}
